package com.solocredit.finance.ui.user.act

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import com.solocredit.finance.R
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaUserLuckyDrawBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.ProAct
import com.solocredit.finance.utils.dialog.LuckyDrawAnimDialog
import com.solocredit.finance.utils.dialog.LuckyDrawPointsDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.utils.helper.MullaUserPointsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/13 19:30
 * @Annotation：抽奖
 */
class MullaUserLuckyDrawAct: ProAct() {
    lateinit var binding: ActMullaUserLuckyDrawBinding

    override fun getMullaRootView(): View {
        binding = ActMullaUserLuckyDrawBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.parentLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)

        binding.ivLanguage.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            binding.ivLanguage.visibility = View.VISIBLE
        }
        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    override fun initMullaListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }

        //客服
        binding.imgKefu.setOnClickListener {
            showMullaKefuDialog("LuckyDraw Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"LuckyDraw Page")
        }

        //语言切换
        binding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"LuckyDraw Page")
            showMullaLanguageDialog("OcrCamera Page", onSelectCallback = {
            })
        }

        //开始抽奖
        binding.btnStartDraw.setOnClickListener {
            showMullaLoading(isTOuchOut = false, isCancel = true)
            onSaveMullaUserPointsAction("luckyDrawUse","-${MullaCustomConfigsHelper.getMullaLuckyDrawPointsUse()}",true)
        }
    }

    override fun initMullaData() {
        //今日剩余抽奖次数
        val luckyDrawCount = MullaCustomDataHelper.getMullaCustomLuckyDrawCount()
        val showTipsText = String.format(getString(R.string.user_lucky_draw_chances_left),"$luckyDrawCount")
        val spString = SpannableString(showTipsText)
        val startIndex = showTipsText.indexOf("$luckyDrawCount")
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFFFFF")), startIndex, showTipsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textChances.text = spString

        //抽奖需要消耗的积分
        val needUsePoints = MullaCustomConfigsHelper.getMullaLuckyDrawPointsUse().toInt()
        //当前剩余积分
        val userPoints = getMullaUserPoints()
        //积分不足
        if (userPoints < needUsePoints){
            binding.btnStartDraw.setBackgroundResource(R.drawable.mulla_luck_draw_btn_tomorrow_bg)
            binding.btnStartDraw.text = getString(R.string.coupon_not_enough)
            binding.btnStartDraw.isEnabled = false
        } else {
            //今日剩余抽奖次数 <= 0
            if (luckyDrawCount <= 0){
                binding.btnStartDraw.setBackgroundResource(R.drawable.mulla_luck_draw_btn_tomorrow_bg)
                binding.btnStartDraw.text = getString(R.string.user_lucky_draw_tomorrow)
                binding.btnStartDraw.isEnabled = false
            } else {
                binding.btnStartDraw.setBackgroundResource(R.drawable.mulla_luck_draw_btn_bg)
                binding.btnStartDraw.text = String.format(getString(R.string.user_lucky_draw_points_time),"$needUsePoints")
                binding.btnStartDraw.isEnabled = true
            }
        }
    }

    /**
     * 显示抽奖动画
     */
    private fun showMullaLuckyDrawAnimDialog(){
        if (isFinishing){
            return
        }
        val animDialog = LuckyDrawAnimDialog(this,object : LuckyDrawAnimDialog.IDialogCallback{
            override fun showComplete() {
                showMullaLoading(isTOuchOut = false, isCancel = true)
                val points = MullaCustomConfigsHelper.getMullaLuckyDrawPoints()
                onSaveMullaUserPointsAction("luckyDrawReceived",points,false)
            }
        })
        animDialog.setCancelable(false)
        animDialog.setCanceledOnTouchOutside(false)
        animDialog.show()
    }

    /**
     * 显示得到积分
     */
    private fun showMullaLuckyDrawReceivePointsDialog(points: String){
        //今日剩余抽奖次数
        val luckyDrawCount = MullaCustomDataHelper.getMullaCustomLuckyDrawCount()
        //保存剩余次数和记录上次抽奖时间
        MullaCustomDataHelper.saveMullaCustomLuckyDrawCount("${luckyDrawCount - 1}")

        if (isFinishing){
            return
        }
        val pointsyDialog = LuckyDrawPointsDialog(this)
        pointsyDialog.setCancelable(true)
        pointsyDialog.setCanceledOnTouchOutside(false)
        pointsyDialog.show()
        pointsyDialog.showMullaUserBirthdayPoints(points)
    }

    /**
     * 抽奖消耗、获得积分
     */
    private fun onSaveMullaUserPointsAction(useType: String,points: String,isUse: Boolean){
        MullaUserPointsHelper.saveMullsUserPointsAction(useType, getString(R.string.points_use_info_lucky_draw),points,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideMullaLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        if (isUse){//抽奖消耗
                            showMullaLuckyDrawAnimDialog()
                        } else {//抽奖得到
                            showMullaLuckyDrawReceivePointsDialog(points)
                        }
                    }
                    else -> {
                        showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideMullaLoading()
            }
        })
    }

    override fun onMullaEvent(event: MullaEventData) {
        if (event.eventType == MullaEventData.TYPE.MULLA_CUSTOM_DATA_REFRESHED){
            initMullaData()
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LUCKY_DRAW_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LUCKY_DRAW_END)
    }
}